import 'package:flutter/material.dart';
import 'package:flutter_wan_android/http/http_exception.dart';
import 'package:toast/toast.dart';
import 'view_state.dart';

///
/// ViewModel的基类
/// 将通过状态修改，重建部件
///
abstract class ViewStateModel with ChangeNotifier {
  /// 防止页面销毁后,异步任务才完成,导致报错
  bool _disposed = false;

  /// 当前的页面状态,默认为idle
  ViewState _viewState;

  ViewState get viewState => _viewState;

  bool get isBusy => viewState == ViewState.busy;

  bool get isIdle => viewState == ViewState.idle;

  bool get isEmpty => viewState == ViewState.empty;

  bool get isError => viewState == ViewState.error;

  ///
  /// 设置状态，并通知部件重建
  ///
  set viewState(ViewState viewState) {
    _viewStateError = null;
    _viewState = viewState;
    notifyListeners();
  }

  ///当前状态错误信息
  AppHttpException _viewStateError;

  AppHttpException get viewStateError => _viewStateError;

  /// 子类可以在构造函数指定需要的页面状态
  /// FooModel():super(viewState:ViewState.busy);
  ViewStateModel({ViewState viewState})
      : _viewState = viewState ?? ViewState.idle {
    debugPrint('ViewStateModel---constructor--->$runtimeType');
  }

  void setIdle() {
    viewState = ViewState.idle;
  }

  void setBusy() {
    viewState = ViewState.busy;
  }

  void setEmpty() {
    viewState = ViewState.empty;
  }

  /// 设置错误信息
  void setError(AppHttpException exception, stackTrace, {String message}) {
    viewState = ViewState.error;
    _viewStateError = exception;
    _printErrorStack(exception, stackTrace);
    onError(viewStateError);
  }

  ///
  /// 返回错误信息在子类中处理
  ///
  void onError(AppHttpException viewStateError) {}

  ///
  /// 显示错误消息
  ///
  void showErrorMessage(BuildContext context, {String message}) {
    if (message != null && message.isNotEmpty) {
      showMessage(context, message);
      return;
    }

    if (viewStateError != null) {
      showMessage(context, viewStateError.message);
    }
  }

  ///
  /// 显示信息
  ///
  void showMessage(BuildContext context, String message) {
    Future.microtask(() {
      Toast.show(message, context);
    });
  }

  @override
  String toString() {
    return 'BaseModel{_viewState: $viewState, _viewStateError: $_viewStateError}';
  }

  @override
  void notifyListeners() {
    if (!_disposed) {
      super.notifyListeners();
    }
  }

  @override
  void dispose() {
    _disposed = true;
    debugPrint('view_state_model dispose -->$runtimeType');
    super.dispose();
  }
}

/// [e]为错误类型 :可能为 Error , Exception ,String
/// [s]为堆栈信息
void _printErrorStack(e, s) {
  debugPrint('''
<-----↓↓↓↓↓↓↓↓↓↓-----error-----↓↓↓↓↓↓↓↓↓↓----->
$e
<-----↑↑↑↑↑↑↑↑↑↑-----error-----↑↑↑↑↑↑↑↑↑↑----->''');
  if (s != null) debugPrint('''
<-----↓↓↓↓↓↓↓↓↓↓-----trace-----↓↓↓↓↓↓↓↓↓↓----->
$s
<-----↑↑↑↑↑↑↑↑↑↑-----trace-----↑↑↑↑↑↑↑↑↑↑----->
    ''');
}
